package com.global.college.utils;

import android.app.Activity;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.android.billingclient.api.BillingClient;
import com.android.billingclient.api.BillingClientStateListener;
import com.android.billingclient.api.BillingFlowParams;
import com.android.billingclient.api.BillingResult;
import com.android.billingclient.api.ProductDetails;
import com.android.billingclient.api.ProductDetailsResponseListener;
import com.android.billingclient.api.Purchase;
import com.android.billingclient.api.PurchasesResponseListener;
import com.android.billingclient.api.PurchasesUpdatedListener;
import com.android.billingclient.api.QueryProductDetailsParams;
import com.android.billingclient.api.QueryPurchasesParams;
import com.global.college.base.baselist.EventBusBean;
import com.global.college.constants.Constant;


import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;


public class GooglePlayUtil implements PurchasesUpdatedListener {

    private final static String TAG = "GooglePlayUtil";

    //单例
    private static GooglePlayUtil instance;

    private String mProductId;

    //连接状态
    private boolean isConnected = false;

    public static GooglePlayUtil getInstance() {
        if (instance == null) {
            instance = new GooglePlayUtil();
        }
        return instance;
    }

    public GooglePlayUtil() {
    }

    private BillingClient billingClient;

    private Activity mActivity;

    public void init(Activity context) {
        Log.i(TAG, "init");
        mActivity = context;
        if (billingClient == null) {
            initBillingClient(context);
        }
        if (!billingClient.isReady()) {
            startConnection();
        }
    }

    private void initBillingClient(Activity context) {
        Log.i(TAG, "initBillingClient");
        billingClient = BillingClient.newBuilder(context)
                .setListener(this)
                .enablePendingPurchases()
                .build();
    }


    /**
     * 连接google结算库
     */
    public void startConnection() {
        BillingClientStateListener listener = new BillingClientStateListener() {
            @Override
            public void onBillingSetupFinished(@NonNull BillingResult billingResult) {
                if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK) {
                    Log.i(TAG, "连接成功");
                    isConnected = true;
                    checkUnconsumed();
                } else {
                    Log.i(TAG, "连接失败：" + billingResult.getResponseCode());
                }
            }

            @Override
            public void onBillingServiceDisconnected() {
                Log.i(TAG, "连接失败");
                // Try to restart the connection on the next request to
                // Google Play by calling the startConnection() method.
            }
        };
        billingClient.startConnection(listener);
    }

    /**
     * 查询已购买未消耗商品
     */
    public void checkUnconsumed() {
        Log.i(TAG, "checkUncounsumed");
        QueryPurchasesParams queryPurchasesParams = QueryPurchasesParams.newBuilder()
                .setProductType(BillingClient.ProductType.INAPP)
                .build();
        billingClient.queryPurchasesAsync(queryPurchasesParams, new PurchasesResponseListener() {
            @Override
            public void onQueryPurchasesResponse(@NonNull BillingResult billingResult, @NonNull List<Purchase> list) {
                Log.i(TAG, "onQueryPurchasesResponse");
                if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK) {
                    if (list.size() > 0) {
                        for (Purchase purchase : list) {
                            Log.i(TAG, "onQueryPurchasesResponse:" + purchase.toString());
                            if ((purchase.getPurchaseState() == Purchase.PurchaseState.PURCHASED) ||
                                    (purchase.getPurchaseState() == 0)) {//按照官方文档，这里应该是1，但是实际上是0
                                // 消耗掉
                                resultCallback(0, purchase.getPackageName(), purchase.getPurchaseToken(),purchase.getProducts().get(0),true);
                            }
                        }
                    }
                }
            }
        });
    }

    @Override
    public void onPurchasesUpdated(@NonNull BillingResult billingResult, @Nullable List<Purchase> purchases) {
        if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK
                && purchases != null) {
            for (Purchase purchase : purchases) {
                Log.i(TAG, "购买成功");

                Log.i(TAG, purchase.toString());
                //  handlePurchase(purchase);
                resultCallback(0, purchase.getPackageName(), purchase.getPurchaseToken(), purchase.getProducts().get(0),false);
            }
        } else if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.USER_CANCELED) {
            // Handle an error caused by a user cancelling the purchase flow.
            Log.i(TAG, "取消购买");
            resultCallback(1, "", "", "",false);
        } else {
            resultCallback(2, "", "", "",false);
            // Handle any other error codes.
            Log.i(TAG, "购买失败:" + billingResult.getResponseCode() + "," + billingResult.getDebugMessage());
//            showUiToast("购买失败:"+billingResult.getResponseCode()+","+billingResult.getDebugMessage());
        }
    }

    // isCheckUnresumed

    /**
     * 支付成功，需要调用后端接口消耗商品
     * @param result 0:成功 1:取消 2:失败
     * @param pkgName
     * @param token
     * @param productId
     * @param isCheckUnresumed 是否未消耗商品，不一定用
     */
    private void resultCallback(int result, String pkgName, String token, String productId, boolean isCheckUnresumed) {
        if (result == 0) {
            EventBus.getDefault().post(new EventBusBean(0, Constant.EventBus.APY_SUCCESS, ""));
        } else if (result == 1) {
            Log.i(TAG, "取消支付");
            EventBus.getDefault().post(new EventBusBean(0, Constant.EventBus.APY_FAIL, ""));
        } else {
            Log.i(TAG, "支付失败");
            EventBus.getDefault().post(new EventBusBean(0, Constant.EventBus.APY_FAIL, ""));
        }
    }

    /**
     * 调用google支付
     * @param productId google play 商品id
     * @param orderId 业务订单id
     */
    public void callGooglePay(String productId, String orderId) {
        if (!isConnected) {
            Log.i(TAG, "无法连接google play");
            resultCallback(3, "", "", "",false);
        }
        if (!billingClient.isReady()){
            Log.i(TAG, "连接断开，重新连接...");
            startConnection();
            return;
        }
        this.mProductId = productId;
        List<QueryProductDetailsParams.Product> productList = new ArrayList<>();
        productList.add(QueryProductDetailsParams.Product.newBuilder()
                .setProductId(productId)
                .setProductType(BillingClient.ProductType.INAPP)
                .build());
        QueryProductDetailsParams queryProductDetailsParams =
                QueryProductDetailsParams.newBuilder()
                        .setProductList(productList)
                        .build();
        Log.i(TAG, "查询商品信息:" + productId);
        billingClient.queryProductDetailsAsync(
                queryProductDetailsParams,
                new ProductDetailsResponseListener() {
                    public void onProductDetailsResponse(BillingResult billingResult,
                                                         List<ProductDetails> productDetailsList) {
                        Log.i(TAG, "查询商品信息成功:" + productDetailsList.get(0).getProductId());
                        mActivity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                startBuy(productDetailsList, orderId);
                            }
                        });

                    }
                }
        );
    }

    private void startBuy(List<ProductDetails> productDetailsList, String orderId) {

        List<BillingFlowParams.ProductDetailsParams> productDetailsParamsList = new ArrayList<>();
        for (ProductDetails productDetails : productDetailsList) {
            productDetailsParamsList.add(BillingFlowParams.ProductDetailsParams.newBuilder()
                    .setProductDetails(productDetails)
//                    .setOfferToken(productDetails.getSubscriptionOfferDetails().get(0).getOfferToken())
                    .build());
        }
        BillingFlowParams billingFlowParams = BillingFlowParams.newBuilder()
                .setProductDetailsParamsList(productDetailsParamsList)
                .setObfuscatedProfileId(orderId)
                .setObfuscatedAccountId("test1234")
                .build();

// Launch the billing flow

        Log.i(TAG, "launchBillingFlow");
        BillingResult billingResult = billingClient.launchBillingFlow(mActivity, billingFlowParams);
        Log.i(TAG, "billingResult:" + billingResult.getResponseCode()+","+billingResult.getDebugMessage());
    }

}
